package sanmubird.club.v8.FunctionParam.lambda;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.stream.Collectors;

/**
 * 环绕执行模式
 * 资源处理(例如处理文件或数据库)时一个常见的模式就是打开一个资源,做一些处理,
 * 然后关闭资源。这个设置和清理阶段总是很类似,并且会围绕着执行处理的那些重要代码。这就
 * 是所谓的环绕执行(execute around)模式
 */
public class LambdaPractise {

    private String processFile(BufferedReaderProcessor bufferedReaderProcessor) throws IOException {
        try (BufferedReader br =
                     new BufferedReader(new FileReader(ClassLoader.getSystemResource("data.txt").getPath()))) {
            return bufferedReaderProcessor.process(br);
        }
    }


    @Test
    public void readOneLine() throws IOException {
        String result = processFile(BufferedReader::readLine);
        System.out.println(result);
    }

    @Test
    public void readTwoLine() throws IOException {
        String result = processFile((BufferedReader br) -> br.readLine() + "\t" + br.readLine());
        System.out.println(result);
    }

    @Test
    public void readAllLine() throws IOException {
        String result = processFile(br -> br.lines().collect(Collectors.joining()));
        System.out.println(result);
    }
}

@FunctionalInterface
interface BufferedReaderProcessor {
    String process(BufferedReader b) throws IOException;
}